<script setup lang="ts">
import type { RoleAssignInfo, User } from '#/api';

import { ref, watch } from 'vue';

import {
  Alert,
  Checkbox,
  CheckboxGroup,
  Col,
  message,
  Modal,
  Row,
  Spin,
} from 'ant-design-vue';

import { assignUserRolesApi, getUserRoleAssignInfoApi } from '#/api';

interface Props {
  visible: boolean;
  userData?: User;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:visible', 'success']);

const confirmLoading = ref(false);
const loading = ref(false);

// 角色列表
const roleList = ref<RoleAssignInfo[]>([]);
const checkedRoleIds = ref<number[]>([]);

// 监听模态框打开状态和用户数据变化
watch(
  () => [props.visible, props.userData] as const,
  async ([visible, userData]) => {
    // 只在模态框打开且有用户数据时加载
    if (visible && userData?.id) {
      await loadUserRoleAssignInfo(userData.id);
    }
  },
);

// 加载用户角色分配信息
async function loadUserRoleAssignInfo(userId: number) {
  loading.value = true;
  try {
    const roles = await getUserRoleAssignInfoApi(userId);
    roleList.value = roles;
    // 提取已分配的角色ID（checked 为 true 的角色）
    checkedRoleIds.value = roles
      .filter((role) => role.checked)
      .map((role) => role.id);

    console.log('📋 加载用户角色信息成功:', {
      userId,
      总角色数: roles.length,
      已分配角色数: checkedRoleIds.value.length,
      已分配角色ID: checkedRoleIds.value,
      角色列表: roles,
    });
  } catch (error) {
    console.error('加载用户角色信息失败:', error);
    message.error('加载用户角色信息失败');
  } finally {
    loading.value = false;
  }
}

// 确定
async function handleOk() {
  if (!props.userData?.id) return;

  try {
    confirmLoading.value = true;
    await assignUserRolesApi(props.userData.id, checkedRoleIds.value);
    message.success('分配角色成功');

    emit('success');
    handleCancel();
  } catch {
    message.error('分配角色失败');
  } finally {
    confirmLoading.value = false;
  }
}

// 取消
function handleCancel() {
  emit('update:visible', false);
  checkedRoleIds.value = [];
  roleList.value = [];
}
</script>

<template>
  <Modal
    :visible="visible"
    title="分配角色"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <Spin :spinning="loading">
      <div class="mb-4">
        <Alert
          message="提示"
          type="info"
          show-icon
        >
          <template #description>
            <div>正在为用户 <strong>{{ userData?.username }}</strong> 分配角色</div>
            <div v-if="roleList.length > 0" class="mt-2">
              共 <strong>{{ roleList.length }}</strong> 个角色，
              已选择 <strong style="color: #1890ff;">{{ checkedRoleIds.length }}</strong> 个
            </div>
          </template>
        </Alert>
      </div>

      <CheckboxGroup v-model:value="checkedRoleIds" style="width: 100%">
        <Row>
          <Col v-for="role in roleList" :key="role.id" :span="24" class="mb-3">
            <div class="role-item">
              <Checkbox :value="role.id" :disabled="role.status === 0">
                <div class="role-info">
                  <div class="role-header">
                    <span class="role-name">{{ role.roleName }}</span>
                    <span class="role-code">({{ role.roleCode }})</span>
                    <span
                      v-if="role.status === 1"
                      class="role-status enabled"
                    >
                      启用
                    </span>
                    <span
                      v-else
                      class="role-status disabled"
                    >
                      禁用
                    </span>
                  </div>
                  <div v-if="role.description" class="role-description">
                    {{ role.description }}
                  </div>
                </div>
              </Checkbox>
            </div>
          </Col>
        </Row>
      </CheckboxGroup>

      <div v-if="roleList.length === 0 && !loading" class="empty-tip">
        暂无可分配的角色
      </div>
    </Spin>
  </Modal>
</template>

<style scoped lang="scss">
.role-item {
  padding: 8px 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background-color: #fafafa;
    border-color: #d9d9d9;
  }
}

.role-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.role-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.role-name {
  font-weight: 500;
  color: #262626;
}

.role-code {
  color: #8c8c8c;
  font-size: 12px;
}

.role-status {
  display: inline-block;
  padding: 0 8px;
  font-size: 12px;
  border-radius: 2px;

  &.enabled {
    color: #52c41a;
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
  }

  &.disabled {
    color: #ff4d4f;
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
  }
}

.role-description {
  color: #8c8c8c;
  font-size: 12px;
  margin-left: 24px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #8c8c8c;
}
</style>
